package com.portal.sso.server.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.portal.sso.core.config.PortalResault;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.exception.WhitelistException;
import com.portal.sso.core.model.ResponseTModel;
import com.portal.sso.core.model.TgtModel;
import com.portal.sso.core.server.AbstractTokenManage;
import com.portal.sso.core.server.PortalUserServer;
import com.portal.sso.core.util.PortalSecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: portal-sso
 * @description: restful方式登录
 * @author: xuduo
 * @create: 2021-04-28 22:47
 * @Version: 1.0
 **/
@Slf4j
@RestController
public class TokenAppLoginController {
    @Autowired
    PortalUserServer portalUserServer;
    @Autowired
    AbstractTokenManage tokenManage;
    @PostMapping("/app/login")
    public String AppLogin(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("username");
        String userPwd = request.getParameter("password");
        String encryKey = request.getParameter("encryKey");
        String appid = request.getParameter("appid");

        if(StrUtil.isEmpty(userId)){
            return JSONUtil.toJsonStr(new ResponseTModel( PortalResault.ERR_NULL_USERID));
        }
        if(StrUtil.isEmpty(userPwd)){
            return JSONUtil.toJsonStr(new ResponseTModel( PortalResault.ERR_NULL_PWD));
        }
        if(StrUtil.isEmpty(appid)){
            return JSONUtil.toJsonStr(new ResponseTModel( PortalResault.NOT_APP_ID));
        }
        //解密
        if(StrUtil.isNotEmpty(encryKey)&& SsoConfig.SSO_REQUEST_PWD_ENCRY.equals(encryKey)){

            try {
                userId = PortalSecureUtil.AesDecode(userId,tokenManage.GetSecret(appid));
                userPwd =  PortalSecureUtil.AesDecode(userPwd,tokenManage.GetSecret(appid));
            } catch (WhitelistException e) {
               log.error(e.getMessage(),e);
                return JSONUtil.toJsonStr(new ResponseTModel( PortalResault.ERR_SSO_NOT_WHITELIST));
            }
        }

        if(portalUserServer.Verification(userId,userPwd)){
            String tgt = tokenManage.GenerateTgt(userId);
            TgtModel tgtModel = new TgtModel(tgt);
            return JSONUtil.toJsonStr(new ResponseTModel(tgtModel,PortalResault.OK.desc()));
        }
        return JSONUtil.toJsonStr(new ResponseTModel( PortalResault.ERR_USER_PWD));
    }

}
